import React, {useEffect, useMemo, useState} from "react";
import {Button, Card, Form, InputNumber, message, Space} from "antd";
import ReactECharts from "echarts-for-react";
import {getTopForecastInterfacesUsingGet} from "@/services/api-backend/trafficForecastController";

type Props={
  type?:number
}
export const TopForecast: React.FC<Props> =(props)=>{
  const {type}=props
  const [data, setData] = useState<API.TrafficForecastVo[]>([])
  const [loading, setLoading] = useState<boolean>(false)
  const [top,setTop]=useState<number>(7)
  const [formRef]=Form.useForm()

  const loadData=async (topN:number=7,hours:number=24)=>{
    try {
      setLoading(true)
      const {data:response}=await getTopForecastInterfacesUsingGet({
        topN,
        hours,
        type})
      if(response){
        setTimeout(()=> {
          setData(response)
          setTop(topN)
        },2300)
      }
    } catch (error) {
      message.error('统计调用次数最多的接口失败');
    }finally {
      setTimeout(()=> setLoading(false),3000)
    }
  }
  const doSubmit=async (values:any)=>{
    if(!values.top&&values.top<=0){
      message.warning("请输入大于0的top");
      return;
    }
    await loadData( values.top || 7,values.hours||24);
  }
  const doReset = async () => {
    formRef.resetFields();
    await loadData( 7);
  };

  // 数据处理（按预测量排序）
  const transformData = useMemo(()=>{
   if(!data||data.length===0){
     return {
       interfaceNames:[],
       interfaces: []
     }
   }

    const sorted = [...data].sort((a, b) =>
      a.predictedRequestCount - b.predictedRequestCount
    );
    // 获取所有唯一的时间标签并排序
    const timeLabels = Array.from(new Set(data.map(item => item.timeLabel || ''))).sort();
    return {
      interfaceNames: sorted.map(item => item.interfaceName),
      predictedCounts: sorted.map(item => item.predictedRequestCount),
      timeLabels
    };
  },[top,data])


// ECharts横向柱状图配置
  const horizontalBarOption =useMemo(()=>{
    const { timeLabels, interfaceNames,predictedCounts } = transformData;
    if(timeLabels?.length===0){
      return {
        title: {
          text: `Top${top} 热门接口预测排行`,
          left: 'center'
        },
        xAxis: { type: 'value', data: [] },
        yAxis: { type: 'category' },
        series: []
      }
    }

    return  {
      title: {
        text: `Top${top} 热门接口预测排行`,
        subtext: `预测时间: ${timeLabels || ''}`,
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: (params) => {
          const data = params[0];
          return `<b>${data.name}</b><br/>预测请求量: <span style="color:#188df0;font-weight:bold">${data.value.toLocaleString()}</span>`;
        }
      },
      grid: {
        left: '15%',
        right: '10%',
        top: '15%',
        bottom: '5%'
      },
      xAxis: {
        type: 'value',
        name: '预测请求量',
        axisLabel: {
          formatter: (value) => {
            if (value >= 10000) {
              return (value / 10000).toFixed(0) + 'w';
            }
            return value;
          }
        }
      },
      yAxis: {
        type: 'category',
        data: interfaceNames,
        axisLabel: {
          fontSize: 12,
          formatter: (value) => {
            // 长名称截断
            return value.length > 20 ? value.substring(0, 20) + '...' : value;
          }
        }
      },
      series: [
        {
          name: '预测请求量',
          type: 'bar',
          data: predictedCounts,
          barWidth: '60%',
          itemStyle: {
            color: (params) => {
              // 根据数值大小设置颜色梯度
              const colors = ['#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272'];
              return colors[params.dataIndex % colors.length];
            },
            borderRadius: [0, 5, 5, 0]
          },
          label: {
            show: true,
            position: 'right',
            formatter: (params) => {
              const value = params.value;
              if (value >= 10000) {
                return (value / 10000).toFixed(1) + 'w';
              }
              return value.toLocaleString();
            },
            color: '#333',
            fontWeight: 'bold'
          }
        }
      ]
    };
  },[top,data])
  useEffect(() => {
    if(type!==undefined){
      loadData()
    }
  },[type])
  return <>
    <Card  style={{marginBottom:24}}>
      <Form
        form={formRef}
        layout="inline"
        onFinish={doSubmit}
        initialValues={{ top: 7,hours:24 }}
      >
        <Form.Item label="TopN" name="top">
          <InputNumber
            placeholder="请输入top"
            style={{ width: 150 }}
            min={1}
            max={90}
          />
        </Form.Item>
        <Form.Item label="预测时段" name="hours">
          <InputNumber
            placeholder="请输入预测时段"
            style={{ width: 150 }}
            min={1}
            max={24}
          />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit" loading={loading}>
              查询
            </Button>
            <Button onClick={doReset} disabled={loading}>重置</Button>
          </Space>
        </Form.Item>

      </Form>
    </Card>
    <ReactECharts
      opts={{ renderer: "canvas" }}
      notMerge={true}
      showLoading={loading}
      option={horizontalBarOption}/>
  </>
}
